﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;

namespace StockholmsStad.Windows.UI.Controls
{
    /// <summary>
    /// Interaction logic for TimeBlockControl.xaml
    /// </summary>
    public partial class TimeBlockControl
    {
        private List<TimeBlock> NearestTimeBlock;
        private List<TimeBlock> AllTimeBlock;
        public TimeBlock SelectedDate { get; set; }

        public TimeBlockControl()
        {
            InitializeComponent();
            InitializeTimeBlocks();

            listViewNearestTime.DataContext = NearestTimeBlock;
            listViewAllTimes.DataContext = AllTimeBlock;
        }

        private static int FindItem(ItemsControl view, TimeBlock timeBlock)
        {
            for (var i = 0; i < view.Items.Count; i++)
            {
                var block = view.Items[i] as TimeBlock;

                if (block != null)
                    if (block.StartDateTime == timeBlock.StartDateTime)
                        return i;
            }

            return -1;
        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var timeBlock = e.AddedItems[0] as TimeBlock;
            if (timeBlock != null)
                TextBoxDate.Text = timeBlock.StartDateTime.ToString("yyyy-MM-dd HH:mm");
        }

        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var timeBlockControl = sender as TimeBlockControl;

            if (timeBlockControl != null)
            {
                timeBlockControl.listViewNearestTime.SelectedIndex =
                    FindItem(timeBlockControl.listViewNearestTime, SelectedDate);
                timeBlockControl.listViewAllTimes.SelectedIndex =
                    FindItem(timeBlockControl.listViewAllTimes, SelectedDate);
            }
        }
    }

}
